<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.itaoke.org All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  Caption <Caption@163.com> QQ 1674653
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Common\Controller\BackendController;

class YoupkuController extends BackendController
{
    private $_tbconfig = null;
    private $_itkconfig = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->_mod       = D('Items');
        $itkia_config     = M('ItemsSite')->where(array(
            'code' => 'itaoke'
        ))->getField('config');
        $this->_itkconfig = unserialize($itkia_config);
        if (!$this->_itkconfig['app_key']) {
            $this->ajaxReturn(0, '请设置爱淘客开放平台appkey');
        }
        $api_config      = M('ItemsSite')->where(array(
            'code' => 'taobao'
        ))->getField('config');
        $this->_tbconfig = unserialize($api_config);
        if (!$this->_tbconfig['app_key']) {
            $this->ajaxReturn(0, '请设置淘宝开放平台appkey');
        }
    }
    public function index()
    {
        $p          = I('p', 1, 'intval');
        $list       = $this->_get_list($p);
        $total      = $list['count'];
        $items_list = (array) $list['item_list'];
        import('ITK.ORG.Page');
        $pager      = new \Page($total, 20);
        $this->assign('page', $pager->show());
        $this->assign('list', $items_list);
        $this->display();
    }
    public function dialog()
    {
        $taodianjin = C('itk_taojindian_html');
        if (strpos($taodianjin, 'text/javascript')) {
            $pid = get_word($taodianjin, 'pid: "', '"');
        } else {
            $pid = $taodianjin;
        }
        if (!$pid) {
            $this->assign('err_msg', '需要获取AdzoneId，请先设置淘点金后采集！');
        }
        $id = I('id', '', 'intval');
        $this->assign('id', $id);
        if (IS_AJAX) {
            $response = $this->fetch();
            $this->ajaxReturn(1, '', $response);
        } else {
            $this->display();
        }
    }
    public function collect()
    {
        $id       = I('id', '', 'intval');
        $cid      = I('cid', '', 'intval');
        $p        = I('p', 1, 'intval');
        $pagesize = 100;
        $tb_top   = $this->_get_tb_top();
        $req      = $tb_top->load_api('TbkUatmFavoritesItemGetRequest');
        $req->setFields('num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,click_url,nick,seller_id,volume,shop_title,zk_final_price_wap,event_start_time,event_end_time,tk_rate,status');
        $req->setPageSize($pagesize);
        $req->setPageNo($p);
        $taodianjin = C('itk_taojindian_html');
        if (strpos($taodianjin, 'text/javascript')) {
            $pid = get_word($taodianjin, 'pid: "', '"');
        } else {
            $pid = $taodianjin;
        }
        if (!$pid) {
            $this->error('需要获取AdzoneId，请先设置淘点金后采集！');
        }
        $pid_arr  = explode("_", $pid);
        $AdzoneId = $pid_arr[3];
        $req->setAdzoneId($AdzoneId);
        $req->setFavoritesId($id);
        $resp       = $tb_top->execute($req);
        $count      = $resp->total_results;
        $resp_items = (array) $resp->results;
        if ($resp->sub_msg) {
            $this->ajaxReturn(0, $resp->sub_msg);
            $this->error($resp->sub_msg);
        }
        if ($resp->msg) {
            $this->ajaxReturn(0, $resp->msg);
            $this->error($resp->msg);
        }
        $item_list = array();
        $up_id     = 0;
        $in_id     = 0;
        foreach ($resp_items['uatm_tbk_item'] as $val) {
            $val               = (array) $val;
            $item              = array();
            $item['cate_id']   = $cid;
            $item['num_iid']   = $val['num_iid'];
            $item['nick']      = $val['nick'];
            $item['sellerId']  = $val['seller_id'];
            $item['pic_url']   = $val['pict_url'];
            $item['title']     = $val['title'];
            $item['click_url'] = $val['click_url'];
            $item['item_url']  = $val['item_url'];
            $item['location']  = $val['provcity'];
            if ($val['user_type'] == 1) {
                $item['shop_type'] = 'B';
            } else {
                $item['shop_type'] = 'C';
            }
            $item['volume']            = $val['volume'];
            $item['price']             = $val['reserve_price'];
            $item['coupon_price']      = $val['zk_final_price'];
            $item['coupon_rate']       = round($item['coupon_price'] / $item['price'], 4) * 10000;
            $item['mcoupon_price']     = $val['zk_final_price_wap'];
            $item['commission']        = ($val['tk_rate'] / 100) * $val['zk_final_price'];
            $item['commission_rate']   = $val['tk_rate'] * 100;
            $item['coupon_start_time'] = strtotime($val['event_start_time']);
            $item['coupon_end_time']   = strtotime($val['event_end_time']);
            $item['astime']            = date("Ymd");
            $item['add_time']          = time();
            $item['ems']               = 1;
            if ($this->_mod->ajax_itk_publish($item)) {
                $in_id++;
            } else {
                $up_id++;
            }
        }
        \Think\Log::record('测试日志信息'.$in_id."失败".$up_id);
        if ($pagesize * $p < $count) {
            $status = 2;
        } else {
            $status = 1;
        }
        IS_AJAX && $this->ajaxReturn($status, '正在采集第' . $p . '页，共有' . $count . '条，添加成功' . $in_id . '条，更新' . $up_id . '条', '', 'collect_dialog');
        $this->success('正在采集第' . $p . '页，共有' . $count . '条，添加成功' . $in_id . '条，更新' . $up_id . '条');
        $this->assign('count', $count);
        $this->assign('list', $item_list);
        if (IS_AJAX) {
            $response = $this->fetch();
            $this->ajaxReturn(1, '', $response);
        } else {
            $this->display();
        }
    }
    private function _get_list($p)
    {
        $tb_top = $this->_get_tb_top();
        $req    = $tb_top->load_api('TbkUatmFavoritesGetRequest');
        $req->setFields('favorites_title,favorites_id,type');
        $req->setPageSize('20');
        $req->setPageNo($p);
        $req->setTime(date("m-d:H:i"));
        $resp       = $tb_top->execute($req);
        $count      = $resp->total_results;
        $resp_items = (array) $resp->results;
        if ($resp->sub_msg) {
            $this->error($resp->sub_msg);
        }
        if ($resp->msg) {
            $this->error($resp->msg);
        }
        $item_list = array();
        foreach ($resp_items['tbk_favorites'] as $val) {
            $val         = (array) $val;
            $item_list[] = $val;
        }
        return array(
            'count' => intval($count),
            'item_list' => $item_list
        );
    }
    private function _get_tb_top()
    {
        vendor('taobao.TopClient');
        vendor('taobao.RequestCheckUtil');
        vendor('taobao.ResultSet');
        $tb_top            = new \TopClient;
        $tb_top->appkey    = $this->_tbconfig['app_key'];
        $tb_top->secretKey = $this->_tbconfig['app_secret'];
        return $tb_top;
    }
}